#include "medicalrecorddetailwidget.h"
#include "ui_medicalrecorddetailwidget.h"
#include "../../network/networkclient.h"
#include "prescriptiondetailwidget.h"
#include <QMessageBox>
#include <QJsonArray>

MedicalRecordDetailWidget::MedicalRecordDetailWidget(const MedicalRecord& record, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MedicalRecordDetailWidget),
    m_record(record) {
    ui->setupUi(this);
    
    // 设置窗口属性
    setWindowTitle("病历详情");
    setWindowFlags(Qt::Window);
    setAttribute(Qt::WA_DeleteOnClose);
    
    // 显示病历信息
    ui->recordIdLabel->setText(QString::number(record.id));
    ui->visitTimeLabel->setText(record.visitTime.toString("yyyy-MM-dd HH:mm:ss"));
    ui->doctorNameLabel->setText(record.doctorName);
    ui->chiefComplaintText->setPlainText(record.chiefComplaint);
    ui->presentIllnessText->setPlainText(record.presentIllness);
    ui->physicalExamText->setPlainText(record.physicalExam);
    ui->diagnosisLabel->setText(record.diagnosis);
    ui->treatmentText->setPlainText(record.treatment);
    ui->notesText->setPlainText(record.notes);
    
    // 调试输出
    qDebug() << "病历详情 - ID:" << record.id << "AppointmentID:" << record.appointmentId;
    
    // 连接网络消息
    connect(&NetworkClient::instance(), &NetworkClient::messageReceived,
            this, &MedicalRecordDetailWidget::onMessageReceived);
}

MedicalRecordDetailWidget::~MedicalRecordDetailWidget() {
    delete ui;
}

void MedicalRecordDetailWidget::on_viewPrescriptionButton_clicked() {
    // 请求获取该病历对应的处方（通过appointment_id查找）
    if (m_record.appointmentId == 0) {
        QMessageBox::warning(this, "提示", "该病历没有关联的预约信息");
        return;
    }
    
    QJsonObject request;
    request["appointment_id"] = m_record.appointmentId;
    NetworkClient::instance().sendRequest(MSG_GET_PRESCRIPTIONS, request);
}

void MedicalRecordDetailWidget::onMessageReceived(MessageType type, const QJsonObject& data) {
    if (type == MSG_GET_PRESCRIPTIONS_RESPONSE) {
        if (data["success"].toBool()) {
            QJsonArray prescriptions = data["prescriptions"].toArray();
            
            if (prescriptions.isEmpty()) {
                QMessageBox::information(this, "提示", "该病历暂无对应处方");
                return;
            }
            
            // 获取第一个处方（暂时按照只有一个处方处理）
            QJsonObject prescriptionObj = prescriptions[0].toObject();
            Prescription prescription = Prescription::fromJson(prescriptionObj);
            
            // 打开处方详细窗口
            PrescriptionDetailWidget *detailWidget = new PrescriptionDetailWidget(prescription, nullptr);
            detailWidget->setWindowModality(Qt::ApplicationModal);
            detailWidget->show();
        } else {
            QMessageBox::warning(this, "错误", data["error"].toString());
        }
    }
}

